package com.willpower.eureka.auth;

/**
 * @author: wen-yi;
 * @date: 2021/10/29 23:51;
 * @Description:
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.willpower.eureka.entity.SysUser;
import com.willpower.eureka.pojo.User;
import com.willpower.eureka.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: wen-yi;
 * @date: 2021/10/27 23:05;
 * @Description: 增强链:增强jwt自定义 而jwt是根据oauth2转换而来
 */
public class MyTokenEnhancer implements TokenEnhancer {
    @Autowired
    private ISysUserService sysUserService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        User principal = (User) oAuth2Authentication.getPrincipal();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(SysUser::getId);
        wrapper.eq(SysUser::getUsername,principal.getUsername());
        SysUser sysUser = sysUserService.getOne(wrapper);
        principal.setId(sysUser.getId());
        principal.setPassword("******");
        Map<String,Object> map = new HashMap<>();
        map.put("status", true);
        map.put("msg", "请求成功");
        map.put("user", principal);
        ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(map);
        return oAuth2AccessToken;
    }
}
